public class BinarySearchTree {
    static class TreeNode {//内部类
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;//根节点

    //找到val值，返回节点的地址
    public TreeNode search(int val) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val < val) {
                cur = cur.right;
            } else if (cur.val > val) {
                cur = cur.left;
            } else {
                return cur;
            }
        }
        return null;
    }

    //插入
    public boolean insert(int key) {
        TreeNode node = new TreeNode(key);
        if (root == null) {
            root = node;
            return true;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if (cur.val < key) {
                parent = cur;
                cur = cur.right;
            } else if (cur.val == key) {
                return false;
            } else {
                parent = cur;
                cur = cur.left;
            }
        }
        if (parent.val > key) {
            parent.left = node;
        } else {
            parent.right = node;
        }
        return true;
    }


    //删除
    public void removeNode(int key){
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null){
            if (cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if (cur.val > key){
                parent = cur;
                cur = cur.left;
            }else {
                remove(cur,parent);
                return;
            }
        }
    }

    //删除cur这个节点，parent是父节点
    private void remove(TreeNode cur, TreeNode parent) {
        if (cur.left == null){
            if (cur == root){
                root = cur.right;
            }else if (cur == parent.left){
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null ){
            if (cur == root){
                root = cur.left;
            }else if (cur == parent.left){
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }

        }else {
            //cur的左右两边都不为空
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left){
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }
    }

















}
